package testplan.servlets;

import testplan.PMF;
import testplan.entities.Tag;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class TagManager extends HttpServlet
{
	private static final String ACT_NEW = "NEW";
	private static final String ACT_DELETE = "DELETE";
	private static final String ACT_UPDATE = "UPDATE";
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        final String action = request.getParameter("action");
        final String tagName = request.getParameter("tag");
        if(ACT_NEW.equalsIgnoreCase(action))
        {
            addTag(tagName);
        }
        else if(ACT_DELETE.equalsIgnoreCase(action))
        {
            deleteTag(tagName);
        }

        List<String> tags = listTag();
        if(tags.isEmpty())
        {
            response.getOutputStream().println("#empty#");
        }
        else
        {
            for (String s : tags)
            {
                response.getOutputStream().println(s);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }

    private void deleteTag(String tag)
    {
        // TODO need transaction
        final PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Tag.class);
        query.setFilter("name == nameParam");
        query.declareParameters("String nameParam");

        List<Tag> tags = (List<Tag>) query.execute(tag);
        if(tags != null && !tags.isEmpty())
        {
            final Tag tagDelete = tags.get(0);
            try
            {
                pm.deletePersistent(tagDelete);
            }
            finally
            {
                pm.close();
            }
        }
    }

    private void addTag(String tag)
    {
        final Tag tagNew = new Tag(tag);
        final PersistenceManager pm = PMF.get().getPersistenceManager();
        try
        {
            pm.makePersistent(tagNew);
        }
        finally
        {
            pm.close();
        }
    }

    private List<String> listTag()
    {
        List<String> result = new ArrayList<String>();
        final PersistenceManager pm = PMF.get().getPersistenceManager();
        try
        {
            List<Tag> all = (List<Tag>) pm.newQuery(Tag.class).execute();
            for (Tag t : all)
            {
                result.add(t.getName());
            }
        }
        finally
        {
            pm.close();
        }
        return result;
    }
}
